package com.firesrc.mail.thread;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Set;

import jodd.cache.Cache;

import com.firesrc.bean.Keyword;
import com.firesrc.bean.Record;
import com.firesrc.mail.search.CacheManager;
import com.firesrc.service.KeywordService;
import com.firesrc.service.RecordService;
import com.firesrc.service.ScheduleExecutorManagerFactory;
import com.firesrc.service.SuperScheduledExecutorManager;
import com.firesrc.service.impl.KeywordServiceImpl;
import com.firesrc.service.impl.RecordServiceImpl;

public class SearchMailRunable implements Runnable {

  private final KeywordService keywordService = new KeywordServiceImpl();
  private SearchMailExecutor executor = new SearchMailExecutor();;

  @Override
  public void run() {
    System.out.println("开始执行搜索邮件任务计划任务" + new Date());
    List<Keyword> keywordList = keywordService.getTopSearchKeywordList();
    if (keywordList.size() <= 0) {
      System.out.println("数据库关键字已经找完 " + new Date());
      SuperScheduledExecutorManager searchMailExecutorManager = ScheduleExecutorManagerFactory.getSearchMailExecutorManager();
      searchMailExecutorManager.stop();
      return;
    }
    Keyword keyword = keywordList.get(0);

    String keywordName = keyword.getName();
    System.out.println(new Date() + "后台线程开始查找关键字<" + keywordName + ">设置找的数量是" + keyword.getSearchcount());
    Set<Record> searchedRecordSet = null;
    try {
      searchedRecordSet = executor.searchMail(keywordName, Integer.toString(keyword.getSearchcount()));
    } catch (IOException e) {
      e.printStackTrace();
    }
    Cache cache = CacheManager.getMailCache();
    RecordService service = new RecordServiceImpl();
    String topic = keyword.getTopic();
    for (Record record : searchedRecordSet) {
      record.setTopic(topic);
      if (cache.get(record.getMail()) == null) {
        try {
          service.add(record);
        } catch (Exception e) {
          e.printStackTrace();
        }
        cache.put(record.getMail(), record);
      }
    }
    if (searchedRecordSet.size() > 0) {
      keywordService.setSearchedByName(keywordName);
    }
    System.out.println("搜索关键字" + keywordName + "完成" + "共找到邮箱-->" + searchedRecordSet.size());
  }

}